import Mock from 'mockjs'

// 模拟延迟
Mock.setup({
  timeout: '200-600'
})

// 用户相关接口
Mock.mock('/api/login', 'post', (options) => {
  const { username, password } = JSON.parse(options.body)
  if (username === 'admin' && password === 'admin123') {
    return {
      code: 200,
      message: '登录成功',
      data: {
        token: 'mock-token-admin',
        user: {
          id: 1,
          username: 'admin',
          name: '管理员',
          role: 'admin'
        }
      }
    }
  } else if (username === 'user' && password === 'user123') {
    return {
      code: 200,
      message: '登录成功',
      data: {
        token: 'mock-token-user',
        user: {
          id: 2,
          username: 'user',
          name: '普通用户',
          role: 'user'
        }
      }
    }
  } else {
    return {
      code: 401,
      message: '用户名或密码错误'
    }
  }
})

Mock.mock('/api/register', 'post', (options) => {
  const { username, password, name } = JSON.parse(options.body)
  return {
    code: 200,
    message: '注册成功',
    data: {
      id: Mock.Random.id(),
      username,
      name,
      role: 'user'
    }
  }
})

// 图书相关接口
const bookCategories = ['文学', '科技', '历史', '艺术', '教育', '经济', '哲学', '社会科学']
const bookLocations = ['A区-1层', 'A区-2层', 'B区-1层', 'B区-2层', 'C区-1层', 'C区-2层']
const publishers = ['人民出版社', '商务印书馆', '科学出版社', '教育出版社', '机械工业出版社']

// 生成模拟图书数据
const generateBooks = (count = 50) => {
  const books = []
  for (let i = 0; i < count; i++) {
    books.push({
      id: i + 1,
      isbn: Mock.Random.id().slice(0, 13),
      title: Mock.Random.ctitle(2, 10),
      author: Mock.Random.cname(),
      publisher: Mock.Random.pick(publishers),
      publishDate: Mock.Random.date('yyyy-MM-dd'),
      category: Mock.Random.pick(bookCategories),
      location: Mock.Random.pick(bookLocations),
      status: Mock.Random.pick(['在馆', '借出']),
      borrowCount: Mock.Random.integer(0, 100),
      description: Mock.Random.cparagraph(1, 3)
    })
  }
  return books
}

const books = generateBooks()

// 获取图书列表
Mock.mock(/\/api\/books(\?.*)?$/, 'get', (options) => {
  // 解析查询参数
  const url = new URL(options.url, 'http://mock')
  const category = url.searchParams.get('category')
  const keyword = url.searchParams.get('keyword')
  const status = url.searchParams.get('status')
  const page = parseInt(url.searchParams.get('page') || '1')
  const limit = parseInt(url.searchParams.get('limit') || '10')
  
  // 过滤图书
  let filteredBooks = [...books]
  if (category) {
    filteredBooks = filteredBooks.filter(book => book.category === category)
  }
  if (keyword) {
    filteredBooks = filteredBooks.filter(book => 
      book.title.includes(keyword) || 
      book.author.includes(keyword) || 
      book.publisher.includes(keyword)
    )
  }
  if (status) {
    filteredBooks = filteredBooks.filter(book => book.status === status)
  }
  
  // 分页
  const start = (page - 1) * limit
  const end = start + limit
  const pageBooks = filteredBooks.slice(start, end)
  
  return {
    code: 200,
    message: '获取成功',
    data: {
      total: filteredBooks.length,
      books: pageBooks
    }
  }
})

// 获取图书详情
Mock.mock(/\/api\/books\/\d+$/, 'get', (options) => {
  const id = parseInt(options.url.match(/\/api\/books\/(\d+)$/)[1])
  const book = books.find(item => item.id === id)
  
  if (book) {
    return {
      code: 200,
      message: '获取成功',
      data: book
    }
  } else {
    return {
      code: 404,
      message: '图书不存在'
    }
  }
})

// 添加图书
Mock.mock('/api/books', 'post', (options) => {
  const newBook = JSON.parse(options.body)
  newBook.id = books.length + 1
  newBook.status = '在馆'
  newBook.borrowCount = 0
  books.push(newBook)
  
  return {
    code: 200,
    message: '添加成功',
    data: newBook
  }
})

// 更新图书
Mock.mock(/\/api\/books\/\d+$/, 'put', (options) => {
  const id = parseInt(options.url.match(/\/api\/books\/(\d+)$/)[1])
  const updateData = JSON.parse(options.body)
  const index = books.findIndex(item => item.id === id)
  
  if (index !== -1) {
    books[index] = { ...books[index], ...updateData }
    return {
      code: 200,
      message: '更新成功',
      data: books[index]
    }
  } else {
    return {
      code: 404,
      message: '图书不存在'
    }
  }
})

// 删除图书
Mock.mock(/\/api\/books\/\d+$/, 'delete', (options) => {
  const id = parseInt(options.url.match(/\/api\/books\/(\d+)$/)[1])
  const index = books.findIndex(item => item.id === id)
  
  if (index !== -1) {
    const deletedBook = books.splice(index, 1)[0]
    return {
      code: 200,
      message: '删除成功',
      data: deletedBook
    }
  } else {
    return {
      code: 404,
      message: '图书不存在'
    }
  }
})

// 借阅相关接口
const borrowRecords = []

// 借书
Mock.mock('/api/borrow', 'post', (options) => {
  const { userId, bookId, borrowDate } = JSON.parse(options.body)
  const book = books.find(item => item.id === bookId)
  
  if (!book) {
    return {
      code: 404,
      message: '图书不存在'
    }
  }
  
  if (book.status === '借出') {
    return {
      code: 400,
      message: '图书已被借出'
    }
  }
  
  // 更新图书状态
  book.status = '借出'
  book.borrowCount += 1
  
  // 创建借阅记录
  const record = {
    id: borrowRecords.length + 1,
    userId,
    bookId,
    bookTitle: book.title,
    borrowDate: borrowDate || Mock.Random.date('yyyy-MM-dd'),
    returnDate: null,
    status: '借出'
  }
  borrowRecords.push(record)
  
  return {
    code: 200,
    message: '借阅成功',
    data: record
  }
})

// 还书
Mock.mock('/api/return', 'post', (options) => {
  const { recordId, returnDate } = JSON.parse(options.body)
  const record = borrowRecords.find(item => item.id === recordId)
  
  if (!record) {
    return {
      code: 404,
      message: '借阅记录不存在'
    }
  }
  
  if (record.status === '已还') {
    return {
      code: 400,
      message: '图书已归还'
    }
  }
  
  // 更新借阅记录
  record.returnDate = returnDate || Mock.Random.date('yyyy-MM-dd')
  record.status = '已还'
  
  // 更新图书状态
  const book = books.find(item => item.id === record.bookId)
  if (book) {
    book.status = '在馆'
  }
  
  return {
    code: 200,
    message: '归还成功',
    data: record
  }
})

// 获取借阅记录
Mock.mock(/\/api\/borrow-records(\?.*)?$/, 'get', (options) => {
  // 解析查询参数
  const url = new URL(options.url, 'http://mock')
  const userId = url.searchParams.get('userId')
  const status = url.searchParams.get('status')
  const page = parseInt(url.searchParams.get('page') || '1')
  const limit = parseInt(url.searchParams.get('limit') || '10')
  
  // 过滤记录
  let filteredRecords = [...borrowRecords]
  if (userId) {
    filteredRecords = filteredRecords.filter(record => record.userId === parseInt(userId))
  }
  if (status) {
    filteredRecords = filteredRecords.filter(record => record.status === status)
  }
  
  // 分页
  const start = (page - 1) * limit
  const end = start + limit
  const pageRecords = filteredRecords.slice(start, end)
  
  return {
    code: 200,
    message: '获取成功',
    data: {
      total: filteredRecords.length,
      records: pageRecords
    }
  }
})

// 用户管理接口
const users = [
  {
    id: 1,
    username: 'admin',
    name: '管理员',
    role: 'admin',
    email: 'admin@example.com',
    phone: '13800138000',
    createTime: '2023-01-01'
  },
  {
    id: 2,
    username: 'user',
    name: '普通用户',
    role: 'user',
    email: 'user@example.com',
    phone: '13900139000',
    createTime: '2023-01-02'
  }
]

// 获取用户列表
Mock.mock(/\/api\/users(\?.*)?$/, 'get', (options) => {
  // 解析查询参数
  const url = new URL(options.url, 'http://mock')
  const keyword = url.searchParams.get('keyword')
  const role = url.searchParams.get('role')
  const page = parseInt(url.searchParams.get('page') || '1')
  const limit = parseInt(url.searchParams.get('limit') || '10')
  
  // 过滤用户
  let filteredUsers = [...users]
  if (keyword) {
    filteredUsers = filteredUsers.filter(user => 
      user.username.includes(keyword) || 
      user.name.includes(keyword) || 
      user.email.includes(keyword)
    )
  }
  if (role) {
    filteredUsers = filteredUsers.filter(user => user.role === role)
  }
  
  // 分页
  const start = (page - 1) * limit
  const end = start + limit
  const pageUsers = filteredUsers.slice(start, end)
  
  return {
    code: 200,
    message: '获取成功',
    data: {
      total: filteredUsers.length,
      users: pageUsers
    }
  }
})

// 获取用户详情
Mock.mock(/\/api\/users\/\d+$/, 'get', (options) => {
  const id = parseInt(options.url.match(/\/api\/users\/(\d+)$/)[1])
  const user = users.find(item => item.id === id)
  
  if (user) {
    return {
      code: 200,
      message: '获取成功',
      data: user
    }
  } else {
    return {
      code: 404,
      message: '用户不存在'
    }
  }
})

// 添加用户
Mock.mock('/api/users', 'post', (options) => {
  const newUser = JSON.parse(options.body)
  newUser.id = users.length + 1
  newUser.createTime = Mock.Random.date('yyyy-MM-dd')
  users.push(newUser)
  
  return {
    code: 200,
    message: '添加成功',
    data: newUser
  }
})

// 更新用户
Mock.mock(/\/api\/users\/\d+$/, 'put', (options) => {
  const id = parseInt(options.url.match(/\/api\/users\/(\d+)$/)[1])
  const updateData = JSON.parse(options.body)
  const index = users.findIndex(item => item.id === id)
  
  if (index !== -1) {
    users[index] = { ...users[index], ...updateData }
    return {
      code: 200,
      message: '更新成功',
      data: users[index]
    }
  } else {
    return {
      code: 404,
      message: '用户不存在'
    }
  }
})

// 删除用户
Mock.mock(/\/api\/users\/\d+$/, 'delete', (options) => {
  const id = parseInt(options.url.match(/\/api\/users\/(\d+)$/)[1])
  const index = users.findIndex(item => item.id === id)
  
  if (index !== -1) {
    const deletedUser = users.splice(index, 1)[0]
    return {
      code: 200,
      message: '删除成功',
      data: deletedUser
    }
  } else {
    return {
      code: 404,
      message: '用户不存在'
    }
  }
})

// 统计数据接口
Mock.mock('/api/statistics', 'get', () => {
  return {
    code: 200,
    message: '获取成功',
    data: {
      totalBooks: books.length,
      availableBooks: books.filter(book => book.status === '在馆').length,
      borrowedBooks: books.filter(book => book.status === '借出').length,
      totalUsers: users.length,
      totalBorrows: borrowRecords.length,
      categoryDistribution: bookCategories.map(category => ({
        name: category,
        value: books.filter(book => book.category === category).length
      })),
      monthlyBorrows: [
        { month: '1月', count: Mock.Random.integer(10, 50) },
        { month: '2月', count: Mock.Random.integer(10, 50) },
        { month: '3月', count: Mock.Random.integer(10, 50) },
        { month: '4月', count: Mock.Random.integer(10, 50) },
        { month: '5月', count: Mock.Random.integer(10, 50) },
        { month: '6月', count: Mock.Random.integer(10, 50) },
        { month: '7月', count: Mock.Random.integer(10, 50) },
        { month: '8月', count: Mock.Random.integer(10, 50) },
        { month: '9月', count: Mock.Random.integer(10, 50) },
        { month: '10月', count: Mock.Random.integer(10, 50) },
        { month: '11月', count: Mock.Random.integer(10, 50) },
        { month: '12月', count: Mock.Random.integer(10, 50) }
      ],
      topBooks: books
        .sort((a, b) => b.borrowCount - a.borrowCount)
        .slice(0, 5)
        .map(book => ({
          id: book.id,
          title: book.title,
          borrowCount: book.borrowCount
        }))
    }
  }
})

export default Mock